package com.example.aiprogrammingassistant.views;

import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.text.IJavaPartitions;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;

public class AIToolView extends ViewPart {
	public static final String ID = "com.example.aiprogrammingassistant.views.AIToolView";
	   private Composite parentComposite;
	    private Text resultText;
	    private SourceViewer sourceViewer;
	    private JavaTextTools javaTextTools;
	@Override
	public void createPartControl(Composite parent) {
		
	
        
        parentComposite = new Composite(parent, SWT.BORDER);
        parentComposite.setLayout(new GridLayout(1, false));

        // 添加标题
        Label titleLabel = new Label(parentComposite, SWT.NONE);
        titleLabel.setText("AI 编程助理");
        titleLabel.setFont(new Font(Display.getDefault(), "Arial", 12, SWT.BOLD));

        // 添加结果展示区域
        resultText = new Text(parentComposite, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
        resultText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        resultText.setEditable(false);

        // 初始化监听器（需与后文代码联动）
        initSelectionListener();
        
     // 在 createPartControl 方法中追加：
        Button explainButton = new Button(parentComposite, SWT.PUSH);
        explainButton.setText("解释代码");
        explainButton.addListener(SWT.Selection, e -> {
            String code = resultText.getText().replace("选中的代码：\n", "");
            // 调用 AI 接口并更新结果
            resultText.setText("AI 分析中...");
            new Thread(() -> {
                String analysisResult = callAIApi(code);  // 模拟AI调用
                Display.getDefault().asyncExec(() -> {
                    resultText.setText(analysisResult);
                });
            }).start();
        });
        
  	  // 正确获取 JavaTextTools 实例（关键修复）
//        javaTextTools = JavaUI.getDefault().getJavaTextTools();
        javaTextTools=JavaPlugin.getDefault().getJavaTextTools();
        SourceViewer sourceViewer = new SourceViewer(parentComposite, null, SWT.V_SCROLL | SWT.H_SCROLL);
        
        // 配置文档分区
        IDocument document = new Document();
        javaTextTools.setupJavaDocumentPartitioner(document);
        sourceViewer.setDocument(document);
        
        
     // 使用 JDT 的配置类
        JavaSourceViewerConfiguration config = new JavaSourceViewerConfiguration(
            javaTextTools.getColorManager(),
            JavaPlugin.getDefault().getCombinedPreferenceStore(),
            null,  // Editor
            IJavaPartitions.JAVA_PARTITIONING
        );
        sourceViewer.configure(config);
	}
    @Override
    public void dispose() {
        // 释放资源（避免内存泄漏）
//        if (javaTextTools != null) {
//            javaTextTools.disconnectPartitioner(sourceViewer.getDocument());
//        }
        super.dispose();
    }
	private void initSelectionListener() {
		IWorkbenchPage page = PlatformUI.getWorkbench()
	            .getActiveWorkbenchWindow()
	            .getActivePage();

	    // 注册全局选择监听器
	    page.addSelectionListener(new ISelectionListener() {
	        @Override
	        public void selectionChanged(IWorkbenchPart part, ISelection selection) {
	            // 仅处理 Java 编辑器的文本选择事件
	            if (part instanceof ITextEditor && selection instanceof ITextSelection) {
	                ITextSelection textSelection = (ITextSelection) selection;
	                String selectedCode = textSelection.getText();
	                updateContent(selectedCode); // 更新视图内容
	            }
	        }
	    });
		
	}

	private String callAIApi(String code) {
		// TODO Auto-generated method stub
		return "AI编程暂未实现";
	}

	// 提供公共方法更新显示内容
    public void updateContent(String code) {
        if (!resultText.isDisposed()) {
            resultText.setText("选中的代码：\n" + code);
        }
    }

    @Override
    public void setFocus() {
        resultText.setFocus();
    }
}